package com.oj.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class Redirect2HttpsConfig {
    private static Integer httpPort;
    @Value("${server.http-port}")
    public void setHttpPort(Integer httpPort){
        Redirect2HttpsConfig.httpPort = httpPort;
    }

    private static Integer httpsPort;
    @Value("${server.redirect-https-port}")
    public void setHttpsPort(Integer httpsPort){
        Redirect2HttpsConfig.httpsPort = httpsPort;
    }

    private static boolean httpsEnable;
    @Value("${server.redirect-https-enable}")
    public void setHttpsEnable(boolean httpsEnable){
        Redirect2HttpsConfig.httpsEnable = httpsEnable;
    }

    @Bean(name = "connector")
    public Connector connector() {
        log.info("Redirect2HttpsConfig: httpPort:" + httpPort +
                ", httpsPort:" + httpsPort + ", httpsEnable:" + httpsEnable);
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(httpPort);
        connector.setSecure(false);
        connector.setRedirectPort(httpsPort);
        return connector;
    }

    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory(Connector connector) {
        TomcatServletWebServerFactory tomcat;
        if (httpsEnable == false) {
            tomcat = new TomcatServletWebServerFactory();
        } else {
            tomcat = new TomcatServletWebServerFactory() {
                @Override
                protected void postProcessContext(Context context) {
                    SecurityConstraint securityConstraint = new SecurityConstraint();
                    securityConstraint.setUserConstraint("CONFIDENTIAL");
                    SecurityCollection collection = new SecurityCollection();
                    collection.addPattern("/*");
                    securityConstraint.addCollection(collection);
                    context.addConstraint(securityConstraint);
                }
            };
        }
        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;

    }
}
